/*
 * Copyright 2025 arisgo@163.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.arisgo.cloud.common.utils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author Arisgo
 * @since 2024/1/19
 */
public class ReflectUtil {

    public static Field getField(Class<?> clazz, String column) {
        if (ArgsUtil.isAnyNull(clazz, column)) {
            return null;
        }
        try {
            return clazz.getDeclaredField(column);
        } catch (NoSuchFieldException e) {
            return getField(clazz.getSuperclass(), column);
        }
    }

    public static Field getField(Object object, String column) {
        if (null == object) {
            return null;
        }
        return getField(object.getClass(), column);
    }

    /**
     * 获取类中的指定字段.
     *
     * @param clazz   类名
     * @param columns 字段数组
     */
    public static List<Field> getFields(Class<?> clazz, String... columns) {
        if (Objects.isNull(clazz) || Objects.isNull(columns)) {
            return Collections.emptyList();
        }
        List<Field> fields = getAllFields(clazz);
        if (ArgsUtil.isEmpty(fields)) {
            return Collections.emptyList();
        }
        List<String> list = new ArrayList<>(List.of(columns));
        for (String column : columns) {
            list.add(StringUtil.underlineToCamel(column));
        }
        return fields.stream().filter(c -> list.contains(c.getName())).collect(Collectors.toList());
    }

    /**
     * 获取类中的全部属性.
     *
     * @param object 类名
     */
    public static List<Field> getAllFields(Class<?> object) {
        Class<?> clazz = object;
        List<Field> fields = new ArrayList<>(10);
        while (null != clazz) {
            fields.addAll(new ArrayList<>(List.of(clazz.getDeclaredFields())));
            clazz = clazz.getSuperclass();
        }
        return fields;
    }

}
